package com.liqi.frame.comm.filter;

import com.liqi.frame.comm.Constants;
import com.liqi.frame.comm.session.OnlineSession;
import com.liqi.frame.comm.session.OnlineSessionDAO;
import com.liqi.frame.comm.task.AsyncFactory;
import com.liqi.frame.comm.task.AsyncManager;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Date;

/**
 * 同步Session数据到Db
 * @author liqi on 2020/1/20 0020. liqiwork@qq.com
 */
public class OnlineSessionSyncFilter extends PathMatchingFilter {
    @Autowired
    private OnlineSessionDAO onlineSessionDAO;
    
    /**
     * 同步会话数据到DB 一次请求最多同步一次 防止过多处理 需要放到Shiro过滤器之前
     */
    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        OnlineSession session = (OnlineSession) request.getAttribute(Constants.ONLINE_SESSION);
        // 如果session stop了 也不同步
        // session停止时间，如果stopTimestamp不为null，则代表已停止
        if (session != null && session.getUserId() != null && session.getStopTimestamp() == null) {
            onlineSessionDAO.syncToDb(session);
        }
        return true;
    }
}
